<?php

namespace App\Models;

use App\EmptyObject;
use App\MongoModel as Model;
use App\Services\AdminService;
use Faker\Provider\DateTime;
use Illuminate\Support\Facades\Auth;
use \Services;

/**
 * Class Project
 * @package  App\Models
 * @property string id
 * @property string group_id    所属组织的ID
 * @property string start_time  项目开始时间
 * @property string end_time    项目结束时间
 * @property string type        项目类型
 * @property string title       项目名称
 * @property int    users       项目负责的操作员
 * @property string status      项目审核状态
 * @property string wx_id       关联的微信号id
 * @property array plugins
 * <code>
 * [
 *   shihui: [
 *      "key": "SH0001",
 *      "title": "xxxxx服务社",
 *   ],
 * ]
 * </code>
 */
class Project extends Model
{
    protected $fillable = [
        'group_id',
        'start_time',
        'end_time',
        'type',
        'title',
        'users',
        'plugins',
        'logs',
        'status',
        'wx_id',
    ];

    public function scopeSearch($query, $inputs){
        if(!empty($inputs)){
            return $query->where(function ($querys) use ($inputs){
                if (!empty($inputs['mobile'])) {
                    $wx_id = WxClient::where('mobile', $inputs['mobile'])->get()->pluck('id')->all();
                    $querys->whereIn('wx_id', $wx_id);
                }
                if (!empty($inputs['nickName'])) {
                    $wx_id = WxClient::where('nickName', 'like', "%{$inputs['nickName']}%")->get()->pluck('id')->all();
                    $querys->whereIn('wx_id', $wx_id);
                }
                if (!empty($inputs['user_id'])) {
                    // user_id 填写的是用户的名字
                    $user_ids = User::where('name', 'like', "%{$inputs['user_id']}%")->get()->pluck('id')->all();
                    $querys->whereIn('users', $user_ids);
                    //$querys->where('users', $inputs['user_id']);
                }
                if (!empty($inputs['date'][0]) && !empty($inputs['date'][1])) {
                    $start = $inputs['date'][0];
                    $end = $inputs['date'][1];
                    $date1 = new \DateTime($start);
                    $date2 = new \DateTime($end);

                    $start_time = $date1->getTimestamp();
                    $end_time = $date2->getTimestamp();
                    $start_time = strtotime(date('Y-m-d', $start_time));
                    $end_time = strtotime(date('Y-m-d', $end_time))+86400;
                    $querys->where('start_time', '>=', $start_time)->where('end_time', '<=', $end_time);
                }
                if(isset($inputs['status']) && in_array($inputs['status'], [0,1,2,3,4])){
                    $querys->where('status', $inputs['status']);
                }
                if (!empty($inputs['project_id'])) {
                    // project_id填写的是项目title
                    $project_ids = Project::where('title', 'like', "%{$inputs['project_id']}%")->get()->pluck('id')->all();
                    $querys->find($project_ids);
                }
                if (!empty($inputs['contact']['nickName'])) {
                    
                    $inputs['contacts'] = array_dot($inputs['contact']);
                    $inputs['contacts'] = implode(',', $inputs['contacts']);
                    $projects = Customer::where('socialInfo.wechat.nickName', 'like', "%{$inputs['contacts']}%")
                        ->get()->pluck('projects')->all();
                    $pro_ids = [];
                    foreach ($projects as $v) {
                        $pro_ids = array_merge($pro_ids ,array_keys($v));
                    }
                    $arr = array_unique($pro_ids);
                    $querys->whereIn('_id', $arr);

                }
            });
        }
    }

    //TODO:以后更改为脚本修改状态
    //0:审核中 2：审核未通过 1：未启动 3：已启动 4：已结束
    public function checkStatus($changeStatus = false) {
        $status = $this->status;
        if (($this->status !== 0 && $this->status !== 2) || $changeStatus) {
            if (empty($this->date)) {
                $this->status = 3;
            } else {
                $now = date("Y-m-d");
                if ( $this->date[0] <= $now
                    && $now <= $this->date[1]) {
                    $this->status = 3;
                } else if ($this->date[1] < $now) {
                    $this->status = 4;
                } else {
                    $this->status = 1;
                }
            }
        }
        if ($this->status !== $status) {
            $this->save();
        }
    }

    public function scopeFindByUser($query, $_user = null) {
        $user = is_null($_user) ? request()->user() : $_user;
    }

    public function canDeleteWx($wx_id) {
        $result = [];
        foreach ($wx_id as $value) {
            $wxClient = WxClient::find($value);
            if (!is_null($wxClient)) {
                if (is_array($wxClient->contacts) && !count($wxClient->contacts)) {
                    array_push($result, $value);
                } else if (!is_array($wxClient->contacts)) {
                    array_push($result, $value);
                }
            } else {
                array_push($result, $value);
            }
        }
        return $result;
    }

    public function canAddWx($wx_id) {
        $result = [];
        foreach ($wx_id as $value) {
            $wxClient = WxClient::where([
                'company_id' => Auth::User()->company_id,
                '_id' => $value
            ])->whereIn('project_id', ['', null])->count();
            if ($wxClient) {
                array_push($result, $value);
            }
        }
        return $result;
    }

    public function wxClients() {
        return $this->hasMany(WxClient::class);
    }

    public function group() {
        return $this->belongsTo(Group::class);
    }
}
